/*
产生 S 盒
 */
package generate

import (
	"AES/GF"
)

var S [][]byte = S_Generate()


func change(n byte) byte {
	re := byte(0)
	for i := 0; i < 8; i++ {
		t1 := (n >> i) & 0x1
		t2 := (n >> ((i + 4)%8)) & 0x1
		t3 := (n >> ((i + 5)%8)) & 0x1
		t4 := (n >> ((i + 6)%8)) & 0x1
		t5 := (n >> ((i + 7)%8)) & 0x1
		t6 := (byte(99) >> i) & 0x1
		re = ((t1 ^ t2 ^ t3 ^ t4 ^ t5 ^ t6) << i) | re
	}
	return byte(re)
}

func S_Generate() [][]byte {
	S := make([][]byte, 16)
	for i := 0; i < 16; i++ {
		S[i] = make([]byte, 16)
	}
	for i := 0; i < 16; i++ {
		for j := 0; j < 16; j++ {
			S[i][j] = change(GF.Inverse(byte(i * 16 + j)))
		}
	}
	return S
}

func S_Change(p byte) byte {
	f := p / 16
	l := p % 16
	return S[f][l]
}

/*func SBox(p *[][]byte) (result [][]byte) {
	s := S_Generate()
	for i := 0; i < len(*p); i++ {
		for j := 0; j < len((*p)[i]); j++ {
			p := (*p)[i][j]
			f := p / 16
			l := p % 16
			result[i][j] = s[f][l]
		}
	}
	return result
}*/


